package com.oliver.picturebackendopenfign.feignClient;

import com.oliver.picturebackendcommon.exception.BusinessException;
import com.oliver.picturebackendcommon.exception.ErrorCode;
import com.oliver.picturebackendcommon.model.enums.UserRoleEnum;
import com.oliver.picturebackendcommon.model.vo.UserVO;
import com.oliver.picturebackendmodel.model.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

import static com.oliver.picturebackendcommon.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author snow
* @description 针对表【user(用户)】的数据库操作Service
* @createDate 2024-12-10 20:48:32
*/
@FeignClient(name = "picture-backend-user-service",path = "/api/user/inner")
public interface UserFeignClient {

    @GetMapping("/get/id")
    User getById(@RequestParam("userId") Long userId);

    @GetMapping("/get/ids")
    List<User> listByIds(@RequestParam("userIdSet") Collection<Long> userIdSet);


    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    default User getLoginUser(HttpServletRequest request){
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接返回上述结果）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }


    /**
     * 是否为管理员
     *
     * @param user
     * @return
     */
    default boolean isAdmin(User user){
        return (null != user && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole()));
    }

    default UserVO getUserVO(User user){
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

}
